﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace PizzaLunch
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //MainControl MT = new MainControl();
        CollectionViewSource TweetsView;
        CollectionViewSource CommentsView;
        CollectionViewSource FriendsView;
        CollectionViewSource FansView;

        public MainWindow()
        {
            InitializeComponent();
            TweetsView = (CollectionViewSource)(this.Resources["TweetsView"]);
            CommentsView = (CollectionViewSource)(this.Resources["CommentsView"]);
            TweetsView.SortDescriptions.Add(new SortDescription("DateUpdate", ListSortDirection.Descending));
            CommentsView.SortDescriptions.Add(new SortDescription("DateUpdate", ListSortDirection.Descending));

            FriendsView = (CollectionViewSource)(this.Resources["FriendsView"]);
            FriendsView.SortDescriptions.Add(new SortDescription("ShowName", ListSortDirection.Ascending));
            FansView = (CollectionViewSource)(this.Resources["FansView"]);
            FansView.SortDescriptions.Add(new SortDescription("ShowName", ListSortDirection.Ascending));

            MainControl.UpdateTweets = (x) =>
            {
                Dispatcher.BeginInvoke(new MainControl.UpdateTweetsDel((ti) =>
                    {
                        if (ti.SourceItem != null)
                            ti.HasOrigin = true;
                        else
                            ti.HasOrigin = false;
                        if (MainControl.ItemList.Contains(ti))
                            return;
                        MainControl.ItemList.Add(ti);
                    }
                    ), x);
            };

            MainControl.UpdateComments = (x,y) =>
            {
                Dispatcher.BeginInvoke( new MainControl.UpdateCommentsDel( (ti,tiComment) =>
                    {
                        if (ti.Comments == null)
                            ti.Comments = new TweetList();
                        if (ti.Comments.Contains(tiComment))
                            return;
                        ti.Comments.Add(tiComment);
                    }
                    ), x, y);
            };

            MainControl.UpdateFans = (x, y, z) =>
            {
                Dispatcher.BeginInvoke(new MainControl.UpdateFansDel((user, fans, type) =>
                {
                    if (!MainControl.AllUserList.Contains(fans))
                        MainControl.AllUserList.Add(fans);

                    if (type == UserInfo.UserType.USER_FANS)
                    {
                        if (!user.FansList.Contains(fans))
                            user.FansList.Add(fans);
                    }
                    else
                    {
                        if (!user.FriendsList.Contains(fans))
                            user.FriendsList.Add(fans);
                    }
                }
                    ), x, y, z);
            };

            MainControl.UpdateUserTimeline = (x, y) =>
            {
                Dispatcher.BeginInvoke(new MainControl.UpdateUserTimelineDel((user, ti) =>
                {
                    if (ti.SourceItem != null)
                        ti.HasOrigin = true;
                    else
                        ti.HasOrigin = false;
                    if (user.ItemList.Contains(ti))
                        return;
                    user.ItemList.Add(ti);
                }
                    ), x, y);
            };

            MainControl.UpdateAllUser = (x,y) =>
            {
                Dispatcher.BeginInvoke(new MainControl.UpdateAllUserDel((user,ti) =>
                {
                    if (user.GetID(ti.Account) == MainControl.me.GetID(ti.Account))
                    {
                        ti.IsSelf = true;
                        ti.Author = MainControl.me;
                    }
                    else
                        ti.IsSelf = false;
                    UserInfo olduser = MainControl.AllUserList.SingleOrDefault((u) =>
                    {
                        if (u.Account == ti.Account && u.GetID(u.Account) == user.GetID(user.Account))
                            return true;
                        return false;
                    });
                    if (olduser == null)
                    {
                        MainControl.AllUserList.Add(user);
                        ti.Author = user;
                    }
                    else
                    {
                        ti.Author = olduser;
                    }
                }
                    ), x,y);
            };

            //MainControl.Init();
            MainControl.Start();
            menuCompose.ItemsSource = MainControl.AllAcount;
            SetUser(null);

            //TweetsView.Source = MainControl.ItemList;
            //contentUserInfo.Content = MainControl.me;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            MainControl.Paused = true;
            Login logWindow = new Login();
            logWindow.ShowDialog();
            MainControl.Paused = false;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            MainControl.Clear();
        }

        private void TweetItemList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            contentDetail.Visibility = Visibility.Visible;
            ReFreshComments();
            /*TweetItem ti = lbTweetItem.SelectedItem as TweetItem;
            if (ti == null)
                return;
            string sb;
            sb = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\" ><html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> <body><div><div><strong>";
            sb += "<image src=\"" + ti.Author.HeadUrl + "\" width=50 height=50/>";
            sb += ti.Author.ShowName;
            if (ti.Author.VIP)
                sb += "<iamge src=\"vipV.gif\" />";
            sb += "</strong>发表于";
            sb += ti.DateUpdate.ToString("F");
            sb += "</div><div>";
            sb += ti.Content;
            sb += "</div>";
            sb += "</body></html>";
            webShow.NavigateToString(sb);*/
        }

        private void btCompose_Click(object sender, RoutedEventArgs e)
        {
            MainControl.Paused = true;
            MainControl.Compose(textCompose.Text);
            MainControl.Paused = false;
            textCompose.Text = "";
            MainControl.RefreshQuery();
        }

        private void btRetweet_Click(object sender, RoutedEventArgs e)
        {
            TweetItem ti = lbTweetItem.SelectedItem as TweetItem;
            if (ti == null)
                return;

            MainControl.Paused = true;
            if (ti.Retweet(textComment.Text))
                textComment.Text = "";
            ReFreshComments();
            MainControl.Paused = false;
        }

        private void btComment_Click(object sender, RoutedEventArgs e)
        {
            TweetItem ti = lbTweetItem.SelectedItem as TweetItem;
            if (ti == null)
                return;

            MainControl.Paused = true;
            if (ti.Comment(textComment.Text))
                textComment.Text = "";
            ReFreshComments();
            MainControl.Paused = false;
        }

        private void btRefresh_Click(object sender, RoutedEventArgs e)
        {
            MainControl.RefreshQuery();
        }

        public void ReFreshComments()
        {
            TweetItem ti = lbTweetItem.SelectedItem as TweetItem;
            if (ti == null)
                return;
            MainControl.AddCommentsJob(ti);
            CommentsView.Source = ti.Comments;
        }

        private void btRefreshComment_Click(object sender, RoutedEventArgs e)
        {
            ReFreshComments();
        }

        private void btUserList_Click(object sender, RoutedEventArgs e)
        {
            SetUser(null);
            //UserList userListWnd = new UserList(MainControl.me);
            //userListWnd.ShowDialog();
        }

        private void btDeleteTweet_Click(object sender, RoutedEventArgs e)
        {
            Button btdel = (Button)sender;
            if (btdel == null)
                return;
            TweetItem ti = (TweetItem)btdel.Tag;
            if (ti == null)
                return;
            ti.Delete();
        }

        private void Image_TweetItem_MouseDown(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement btdel = (FrameworkElement)sender;
            if (btdel == null)
                return;
            TweetItem ti = (TweetItem)btdel.Tag;
            if (ti == null || ti.Author == null)
                return;

            SetUser(ti.Author);
        }

        private void Image_UserInfo_MouseDown(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement btdel = (FrameworkElement)sender;
            if (btdel == null)
                return;
            UserInfo user = (UserInfo)btdel.Tag;
            if (user == null)
                return;

            SetUser(user);
        }

        private void SetUser(UserInfo user)
        {
            if (user == null || user.GetType() == MainControl.me.GetType())
            {
                if (user == null)
                {
                    user = MainControl.me;
                    TweetsView.Source = MainControl.ItemList;
                }
                else
                {
                    TweetsView.Source = MainControl.me.ItemList;
                }

                contentUserInfo.Content = MainControl.me;
                FriendsView.Source = MainControl.me.FriendsList;
                FansView.Source = MainControl.me.FansList;

                foreach (TweetAccount tac in MainControl.AllAcount)
                {
                    MainControl.AddQueryUserTimelineJob(tac, MainControl.me);
                    if (!MainControl.me[tac].FriendsCompleted)
                    {
                        user.FriendsList.Clear();
                        MainControl.AddQueryFriendsJob(tac, user, 0);
                    }
                    if (!MainControl.me[tac].FansCompleted)
                    {
                        user.FansList.Clear();
                        MainControl.AddQueryFansJob(tac, user, 0);
                    }
                }
            }
            else
            {
                if (!user.Updated)
                    user.GetUserInfo();

                TweetsView.Source = user.ItemList;
                contentUserInfo.Content = user;
                FriendsView.Source = user.FriendsList;
                FansView.Source = user.FansList;

                MainControl.AddQueryUserTimelineJob(user.Account, user);
                if (!user[user.Account].FriendsCompleted)
                {
                    user.FriendsList.Clear();
                    MainControl.AddQueryFriendsJob(user.Account, user, 0);
                }
                if (!user[user.Account].FansCompleted)
                {
                    user.FansList.Clear();
                    MainControl.AddQueryFansJob(user.Account, user, 0);
                }
            }

            if (TweetsView.View.CurrentItem == null)
                contentDetail.Visibility = Visibility.Hidden;
        }

        private void lbFriends_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserInfo user = lbFriends.SelectedItem as UserInfo;
            if (user == null)
                return;
            int iPos = lbFans.Items.IndexOf(user);
            if (iPos >= 0)
            {
                lbFans.SelectedIndex = iPos;
                lbFans.ScrollIntoView(lbFans.Items[iPos]);
            }
        }

        private void lbFans_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserInfo user = lbFans.SelectedItem as UserInfo;
            if (user == null)
                return;
            int iPos = lbFriends.Items.IndexOf(user);
            if (iPos >= 0)
            {
                lbFriends.SelectedIndex = iPos;
                lbFriends.ScrollIntoView(lbFriends.Items[iPos]);
            }
        }

        private void btConfig_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Image_CopyToText(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement btdel = (FrameworkElement)sender;
            if (btdel == null)
                return;
            TweetItem ti = (TweetItem)btdel.Tag;
            if (ti == null || ti.Author == null)
                return;

            Clipboard.SetDataObject(ti.Content);
            MessageBox.Show("微博内容已复制");
        }

        private void Image_CopyImage(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement btdel = (FrameworkElement)sender;
            if (btdel == null)
                return;
            TweetItem ti = (TweetItem)btdel.Tag;
            if (ti == null || ti.Author == null)
                return;

            Clipboard.SetDataObject(ti.Image);
            MessageBox.Show("图片内容已复制");
        }

        private void Image_OpenWeb(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement btdel = (FrameworkElement)sender;
            if (btdel == null)
                return;
            TweetItem ti = (TweetItem)btdel.Tag;
            if (ti == null || ti.Author == null)
                return;

            System.Diagnostics.Process.Start(ti.GetUrl());
        }

        /*
        private void expComment_Collapsed(object sender, RoutedEventArgs e)
        {
            expComment.Height = 30;
        }

        private void expComment_Expanded(object sender, RoutedEventArgs e)
        {
            expComment.Height = 260;
        }*/
    }
}